package capricornus.components.flower
{
	import capricornus.core.StageManager;
	
	import flash.display.Sprite;
	import flash.events.Event;

	/**
	 * 播放鲜花 
	 * @author kael
	 * 
	 */	
	public class FlowerManager
	{
		private static var _instance:FlowerManager = null;
		private var _layer:Sprite;
		
		private var _arrNum:Array = [];
		private var _arrFlowerLayer:Array = [];
		
		public function FlowerManager()
		{
			init();
		}
		
		private function init():void
		{
			_layer = new Sprite();
			_layer.mouseChildren = false;
			_layer.mouseEnabled = false;
			
//			EventCenter.addEventListener( CenterEvent.HIDE_PLAYER_CHANGED, onHidePlayerChanged, 0 );
		}
		
		private static function get instance():FlowerManager
		{
			if( _instance==null )
			{
				_instance = new FlowerManager();
			}
			return _instance;
		}
		
		private function onHidePlayerChanged( e:* ):void
		{
			if( e.data )
			{
				if( _layer.parent != null )
				{
					_layer.parent.removeChild( _layer );
				}
			}
			else if( _layer.numChildren > 0 )
			{
				StageManager.stage.addChild( _layer );
			}
		}
		
		public function play( num:int ):void
		{
			_arrNum.push( num );
			playNext();
		}
		
		private function playNext():void
		{
			if( _arrFlowerLayer.length < 2 && _arrNum.length > 0 )
			{
				var num:int = _arrNum.shift();
				
				FlowerRefreshController.instance.start();
				if( _layer.stage==null /*&& !DisplaySetting.hideOtherPlayer*/ ) StageManager.stage.addChild( _layer );
				
				var f:FlowerLayer = new FlowerLayer();
				if( num==99 )
				{
					f.play99();
				}
				else f.play999();
				_layer.addChild( f );
				f.addEventListener( "_FINISH", onFinish );
				_arrFlowerLayer.push( f );
			}
			else
			{
				if( _arrFlowerLayer.length==0 && _arrNum.length==0 )
				{
					if( _layer.stage != null ) _layer.parent.removeChild( _layer );
					while( _layer.numChildren > 0 ) _layer.removeChildAt(0);
					
					FlowerRefreshController.instance.stop();
				}
			}
		}
		
		private function onFinish( e:Event ):void
		{
			var f:FlowerLayer = e.currentTarget as FlowerLayer;
			for( var i:int=0; i<_arrFlowerLayer.length; i++ )
			{
				if( _arrFlowerLayer[i]==f )
				{
					_arrFlowerLayer.splice( i, 1 );
					break;
				}
			}
			playNext();
		}
		
		/**
		 * 播放送花特效 
		 * @param num 鲜花朵数
		 * 
		 */		
		public static function play( num:int ):void
		{
			if( num >= 99 )
			{
				instance.play( num );
			}
		}
	}
}